pub mod file_manager;
pub mod interface;
pub mod message;
pub mod network;
pub mod network_discovery;
pub mod sync_manager;
pub mod utils;
use crate::file_manager::FileManager;
use crate::interface::*;
use crate::message::*;
use crate::network::*;
use crate::network_discovery::*;
use crate::sync_manager::*;
use crate::utils::*;
use lazy_static::lazy_static;
use parking_lot::Mutex;
use rand::Rng;
use std::any::Any;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use tauri::async_runtime::spawn;
use tauri::Emitter;
use tauri::Manager;
use tauri::WindowEvent;

pub const FILE_BLOCK_SIZE: u64 = 2 * 1024 * 1024;

lazy_static! {
    // 默认初始的ip地址
    static ref DEFAULT_IP: String = {
        let ips = get_ip_addresses();
        if ips.is_empty() {
            return  "127.0.0.1".to_string();
        }
        ips[0].clone()
    };
    // 全局唯一的实例名称
    static ref INSTANCE_NAME: String = {
        let mut rng = rand::thread_rng();
        (0..8)
            .map(|_| rng.gen_range(b'0'..=b'9') as char) // 可打印 ASCII 范围 (33='!' 到 126='~')
            .collect()
    };

    // 全局唯一的 AppState 实例
    static ref APP_STATE: Arc<AppState> = Arc::new(AppState {
        discover_server: Arc::new(Mutex::new(ServiceDiscovery::new("ZeroTransfer", &INSTANCE_NAME, &DEFAULT_IP ,33445).unwrap())),
        instance_name: Mutex::new(INSTANCE_NAME.clone()),
        tcp_server: Arc::new(TcpServer::new(44556, |data, writer| {
            let app_state = APP_STATE.clone();
            process(app_state, data, writer)
        })),
        target_ip: Mutex::new(DEFAULT_IP.to_string()),
        file_manager: Arc::new(tokio::sync::Mutex::new(FileManager::new("./".to_string(), 4))),
        sync_manager: Arc::new(SyncManager::new()),
    });
}

pub struct AppState {
    discover_server: Arc<Mutex<ServiceDiscovery>>,
    tcp_server: Arc<TcpServer>,
    instance_name: Mutex<String>,
    target_ip: Mutex<String>,
    file_manager: Arc<tokio::sync::Mutex<FileManager>>,
    sync_manager: Arc<SyncManager>,
}

impl AppState {
    pub fn stop(&self) {
        // 停止服务发现
        let mut discover_server = self.discover_server.lock();
        discover_server.stop(); // 假设ServiceDiscovery有stop方法
    }
}

/// 初始化程序
/// 1. 开始应用程序的发现工作
/// 2. 开启本地的 TCP 连接
pub fn init_program() {
    // 初始化实例名字
    let mut instance_name = APP_STATE.instance_name.lock();
    *instance_name = INSTANCE_NAME.to_string();

    // 初始化 TCP 服务器的进程
    init_tcp_server_service();

    // 初始化应用程序的发现工作
    init_network_discover_service();
}

fn init_network_discover_service() {
    let mut discover_server = APP_STATE.discover_server.lock();
    discover_server.start();
}

fn init_tcp_server_service() {
    spawn(async move {
        let state = APP_STATE.clone();
        let server = state.tcp_server.clone();
        let _ = server.start_listen().await;
    });
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_dialog::init())
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![
            get_available_ips,
            get_users,
            rename_discover,
            change_target_ip,
            start_file_transfer,
            get_instance_name
        ])
        .setup(|app| {
            init_program();
            println!("name: {}", INSTANCE_NAME.clone());

            let handler = app.handle().clone();
            thread::spawn(move || loop {
                thread::sleep(Duration::from_secs(5));
                handler.emit("clock_signal", "").unwrap();
            });

            let main_window = Arc::new(app.get_webview_window("main").unwrap());
            main_window.on_window_event(move |event| {
                if let tauri::WindowEvent::CloseRequested { api, .. } = event {
                    APP_STATE.stop();
                }
            });

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
